<?php

namespace app\admin\controller\channel;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use fast\Random;
use app\admin\model\Admin;
use think\Session;

/**
 * 渠道管理
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{
    protected $noNeedLogin = ['login'];
    /**
     * Index模型对象
     * @var \app\admin\model\channel\Index
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\channel\Index;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 一键登录
     */
    public function login()
    {
        // http://sh.ljf.com/admin.php/channel/index/login?code=lvejNkaqk/iysWCjQZ5w8Q==&token=8e4e25c3-e26c-4022-9e20-e929614e414f
        $url = 'index/index';
        $code = $this->request->param('code');
        if(!$code) $this->error('Error Code!');
        $token = $this->request->param('token');
        if(!$token) $this->error('Token Error!');
        $tokenuser = db('Admin')->where(['token'=>$token])->find();
        if(!$tokenuser) $this->error('Token expired.');
        if($tokenuser['status'] != 'normal') $this->error('Your account is invalid.');
        $channel_code = $this->model->decrypt($code);
        $channel = db('Channel')->where(['code'=>$channel_code])->find();
        if(!$channel) $this->error("Can't found this channel.");
        if($channel['status'] != '1') $this->error('Channel status is invalid.');
        $admin = Admin::get(['id' => $channel['admin_id']]);
        if (!$admin) {
            $this->error('Username is incorrect');
        }
        if ($admin['status'] == 'hidden') {
            $this->error('Admin is forbidden');
        }
        $admin = $admin->toArray();
        $admin['loginip'] = request()->ip(); // 过ip检测.该设置开启后,当前仅本机可以访问
        Session::set("admin", $admin);
        
        $this->redirect($url);

    }

    /**
     * 获取一键登录链接
     *
     * @return void
     * @author AriFe.Liu 
     */
    public function getSloginUrl(){
        $ids = $this->request->param('ids');
        #http://sh.ljf.com/admin.php/channel/index/login?code=lvejNkaqk/iysWCjQZ5w8Q==&token=8e4e25c3-e26c-4022-9e20-e929614e414f
        $addon_conf = get_addon_config('channel');
        $channel = db('Channel')->where(['id'=>$ids])->find();
        $code = $channel['code'];
        if(!$code) $this->error('Not find!');
        $code = $this->model->encrypt($code);

        # 后台登录时每次随机生成一个token,点击退出登录时会删除该token,此处我们自己调用相同方法生成一个token并写入到该用户名下
        $token = Random::uuid();        
        $res = db('Admin')->where(['id'=>$channel['admin_id']])->update(['token'=>$token]);
        if($res === false) $this->error("Create token error.");
        $superloginhost = $addon_conf['superloginhost'];        

        $domain = empty($superloginhost) ? $this->request->root(true):$superloginhost;
        $host = parse_url($domain);
        if(isset($host['host'])){
            $host = $host['scheme'].'://'.$host['host'];
        }else{
            $host = 'http://'.$host['path'];
        }

        $url = url('channel/index/login',['code'=>$code,'token'=>$token],false,$host);
        $this->success('ok',null,['url'=>$url]);
    }

    /**
     * 查看
     */
    public function index()
    {        
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','mobile','money','idcard','ratio','truename','createtime','status','code']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    #################

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }                                
                    if($row->status != '0'){
                        exception('该记录已处理!');
                    }
                    if($params['status'] == '1'){
                        $params['id'] = $ids;
                        $this->agree($params);
                    }else if($params['status'] == '2'){
                        if(!isset($params['remark']) || empty($params['remark'])){
                            exception('请在备注中填写驳回理由');
                        }
                    }
                    
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    private function agree($params){    
        $salt = Random::alnum();
        $password = md5(md5(substr($params['mobile'],-6)) . $salt);
        $avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
        $data = [
            'username' => $params['mobile'],
            'nickname' => $params['truename'],
            'password' => $password,
            'salt' => $salt,
            'avatar' => $avatar,
            'createtime' => time(),
            'status' => 'normal',
        ];
        $uid = db('Admin')->insertGetId($data);
        if(!$uid) exception('添加账号失败!');
        $config = get_addon_config('channel');
        $res = db('AuthGroupAccess')->insert([
            'uid' => $uid,
            'group_id' => $config['channel_role_id']
        ]);
        if(!$res) exception('添加账号失败!(INSERT ACCESS FAIL)');
        $res = db('Channel')->where(['id'=>$params['id']])->update([
            'code' => $this->model->encrypt($params['id']),
            'admin_id' => $uid
        ]);
        if($res === false) exception('添加账号失败!(UPDATE CHANNEL INFO ERROR)');
        return true;
    }

}
